﻿namespace Rsdn.SmartApp
{
	using IRegSvc = IRegKeyedElementsService<string, ActivePartInfo>;
	using System;

	/// <summary>
	/// Стандартная реализация <see cref="IActivePartManager"/>
	/// </summary>
	public class ActivePartManager : IActivePartManager
	{
		[ExpectService(Required = false)]
		private IRegSvc _regSvc = null;
		private readonly ElementsCache<string, object> _partsCache;

		/// <include file='../CommonXmlDocs.xml' path='common-docs/def-ctor/*'/>
		public ActivePartManager(IServiceProvider provider)
		{
			this.AssignServices(provider);

			_partsCache = new ElementsCache<string, object>(
				delegate(string name)
				{
					if (_regSvc == null)
						throw new ArgumentException("No active parts registered");
					var info = _regSvc.GetElement(name);
					return info.Type.CreateInstance(provider);
				});
		}

		#region IActivePartManager Members
		/// <summary>
		/// Возвращает признак регистрации по имени.
		/// </summary>
		public bool IsPartRegistered(string name)
		{
			return _regSvc != null && _regSvc.ContainsElement(name);
		}

		/// <summary>
		/// Получить экземпляр active part.
		/// </summary>
		public object GetPartInstance(string name)
		{
			return _partsCache.Get(name);
		}
		#endregion

		#region IActivePartManager Members

		/// <summary>
		/// Возвращает тип active part.
		/// </summary>
		public Type GetPartType(string name)
		{
			if (_regSvc == null)
				throw new ArgumentException("No active parts registered");
			return _regSvc.GetElement(name).Type;
		}
		#endregion
	}
}
